//
//  ShareVC.swift
//  YueChat
//
//  Created by IMac on 2024/10/10.
//

import UIKit

protocol ShareDeleagete :AnyObject {
    
    func shareSelectInfos (targetId:Any,msg:DMCCMessage)
}

enum ShareType:Int {
    case Single = 0
    case Group = 1
    case dapp = 4
    case chat = 5
}

class ShareVC: BaseVC {
    weak var delegate:ShareDeleagete?
    var type = ShareType.Single
    var user = DMCCUser ()
    var group = DMCCGroup()
    var dapp = DMCCDapp()
    var msg = DMCCMessage()
    
    var index = -1
    
    init(type: ShareType, user: DMCCUser = DMCCUser (), group: DMCCGroup = DMCCGroup(), dapp: DMCCDapp = DMCCDapp()) {
        super.init(nibName: nil, bundle: nil)
        self.type = type
        self.user = user
        self.group = group
        self.dapp = dapp
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setup()
        self.getGroup()
    }
    
    @IBAction func onBack(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func done(_ sender: Any) {
        
        if index  == -1 {
            return
        }
        
        let info = self.dataSource[index]
        
        if type == .chat {
            var target = ""
            if info is DMCCUser {
                target = (info as! DMCCUser).userId
            }else {
                target = (info as! DMCCGroup).groupId
            }
            if (gosnConversation.getConversationInfo(target) == nil) {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    geventService.post(.kUpDateConversation, "")
                }
            }
            
            Task {
                let (_,error) = await gosnMessage.sendMessage(target, msg.content! as! OsnMessageContent)
                
                GK_main_async_safe { [self] in
                    if error == nil {
                        if msg.target == target {
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                        }
                        MHAlert.showMessage("转发成功")
                    }else{
                        MHAlert.showMessage("转发失败")
                    }
                }
                
                
            }
//            self.delegate?.shareSelectInfos(info: info)
            dismiss(animated: true)
            return
        }
        
        switch type {
        case .Single:

            break
        case .Group:
//                content = OsnCardMessageContent.card(withTarget: info.userId, type: DMCCCardType(rawValue: 1)!, from: gosnUser.myId()) as OsnCardMessageContent
            break
        case .dapp:

            Task {
                
                if info is DMCCUser {
                    let userInfo = info as! DMCCUser
                    
                    var json = dapp.toJSON()
                    json!["type"] = "card"
                    json!["cardType"] = "litapp"
                    let (msg,error) = await gosnMessage.sendDappMessage(userInfo.userId, json!)//sendCardMessage(user.userId, curentUser.userId)
                    await MainActor.run {
                        if error == nil {
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                        }
                    }
                }else if info is DMCCGroup {
                    let groupInfo = info as! DMCCGroup
                    let (msg,error) = await gosnMessage.sendDappMessage(groupInfo.groupId, dapp.toJSON()!)//sendCardMessage(user.userId, curentUser.userId)
                    await MainActor.run {
                        if error == nil {
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateChatMessage), object: msg)
                        }
                    }
                }
            }
            
            break
        default:
            break
        }
        
        MHAlert.showMessage("发送成功")
    
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
            self.dismiss(animated: true)
        }))
    }
    
    func sendMessage(content: OsnMessageContent, userInfo: DMCCUser) {
        let conv = gosnConversation.initParam(userInfo.userId)//init(param: userInfo.userId, type: 0)]
        
        Task{
            
            _ = await gosnMessage.sendMessage(conv.targetId, content)
            
            
            GK_main_async_safe {
                MHAlert.showMessage("发送成功")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: OsnEvent.RecallMessages.rawValue), object: nil)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
                    self.dismiss(animated: true)
                }))
            }
        }
        
//        DMCCIMService.getInstance().send(conv, content: content, pwd: nil) { hash, timestamp in
//            GK_main_async_safe {
//                self.view.makeToast("发送成功")
//                NotificationCenter.default.post(name: NSNotification.Name(rawValue: OsnEventType.RecallMessages.rawValue), object: nil)
//                DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
//                    self.dismiss(animated: true)
//                }))
//            }
//        } error: { errorCode in
//            // Error handler
//            MHAlert.showError("分享失败")
//        } sendingCB: { str, err in
//            
//        }
    }

    func sendMessage(content: OsnMessageContent, groupInfo: DMCCGroup) {
        let conv = gosnConversation.initParam(groupInfo.groupId)//.init(param: groupInfo.groupId, type: 1)
        
        Task{
            
            let (msg,error) = await gosnMessage.sendMessage(conv.targetId, content)
            
            await MainActor.run {
                if error != nil {
                    GK_main_async_safe {
                        MHAlert.showMessage("发送成功")
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: OsnEvent.RecallMessages.rawValue), object: nil)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
                            self.dismiss(animated: true)
                        }))
                    }
                }
            }
        }
    }
    
    func getGroup() {
        var newGroups = [String]()

        let cons = gosnConversation.getConversationList(OsnConversationType.Group)
        for conv in cons {
            newGroups.append(conv.targetId)
        }
        
        let ids = gosnGroup.listGroupInfo(isFav: true)
        for str in ids {
            newGroups.append(str.groupId)
        }
//        var tempArray = NSMutableArray(array: ids!) as! [String]
        
        
        let sets = NSSet(array: newGroups as [Any])
        let groups = Array(sets)
        
//        counts = dataSource.count
        if groups.isEmpty {
            getListData()
            return
        }
        
        
//        var equal = 0
        for groupId in groups {
            if groupId as! String == group.groupId {
                continue
            }
            let groupInfo = gosnGroup.getGroupInfoDefault(groupId as! String)
            dataSource.append(groupInfo)
        }
        self.getListData()
    }

    @objc func getListData() {
//        dataSource.removeAll()
        self.requestData()
        _ = gosnFriend.getFriendList()
        //DMCCIMService.getInstance().getFriendList(true)
//        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: DispatchWorkItem(block: {
//            self.tableView.mj_header?.endRefreshing()
//        }))
    }
    
    func requestData () {
        let friendArr = gosnFriend.getFriendList()
        var count = friendArr.count
        for f in friendArr {
            if f.userId == user.userId {
                count -= 1
                continue
            }
            self.getUser(friendID: f.friendId, count: count )
        }
    }
    
    func getUser (friendID:String,count:Int) {
        let user = gosnUser.getUserInfoDefault(friendID) as DMCCUser
        dataSource.append(user)
        if dataSource.count == count {
            GK_main_async_safe {
                self.tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    //MARK: 设置表头的高度。如果使用自定义表头，该方法必须要实现，否则自定义表头无法执行，也不会报错
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        let user = dataSource[indexPath.row]

        
        if user is DMCCUser {
            let info = user as! DMCCUser
            if info.uiData as! String == "1" {
                cell.selectImg.isHidden = false
            }else{
                cell.selectImg.isHidden = true
            }
            cell.setUserInfo(userInfo: info)
        }else if user is DMCCGroup {
            let info = user as! DMCCGroup
            if info.uiData as! String == "1" {
                cell.selectImg.isHidden = false
            }else{
                cell.selectImg.isHidden = true
            }
            cell.setGroup(group: info)
//            cell.setGroup(group: user as! GroupInfo)
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        self.index = indexPath.row
        
        let user = dataSource[indexPath.row]
        
        for user in dataSource {
            if user is DMCCUser {
                let info = user as! DMCCUser
                info.uiData = ""
            }else if user is DMCCGroup {
                let info = user as! DMCCGroup
                info.uiData = ""
            }
        }
        
        if user is DMCCUser {
            let info = user as! DMCCUser
            info.uiData = info.uiData as! String == "1" ? "" : "1"
        }else if user is DMCCGroup {
            let info = user as! DMCCGroup
            info.uiData = info.uiData as! String == "1" ? "" : "1"
        }
        self.tableView.reloadData()
    }
    
    
    func setup () {

        tableStytle = .plain
        tableView.frame = CGRect(x: 0, y: GKNavHeight, width: kScreenWidth, height: kScreenHeight - GKNavHeight)
//        let head = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(getListData))
//        head.lastUpdatedTimeLabel?.isHidden = true
//        head.stateLabel?.isHidden = true
//        self.tableView.mj_header = head
        tableView.separatorInset = UIEdgeInsets(top: 0, left: 76, bottom: 0, right: 0)
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
    }
}

